package com.liy.framework.common.utils;

import com.liy.framework.common.extvo.LoginInfo;
import java.util.HashMap;
import java.util.Map;


public class ContextHandler {

    /*
    * 线程局部变量
    */
    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal();

    public ContextHandler() {}

    public static void set(String key, Object value) {
        Map<String, Object> map = (Map)threadLocal.get();
        if (map == null) {
            map = new HashMap();
            threadLocal.set(map);
        }

        ((Map)map).put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = (Map)threadLocal.get();
        if (map == null) {
            map = new HashMap();
            threadLocal.set(map);
        }

        return ((Map)map).get(key);
    }

    public static String getUserID() {
        LoginInfo user = getLoginUser();
        return user == null ? null : user.getId();
    }

    public static String getJwtToken() {
        Object value = get("JwtToken");
        return returnObjectValue(value);
    }

    public static String getAuthKey() {
        Object value = get("AuthKey");
        return returnObjectValue(value);
    }

    public static LoginInfo getLoginUser() {
        LoginInfo value = (LoginInfo)get("login_user");
        return value;
    }

    public static void setJwtToken(String token) {
        set("JwtToken", token);
    }

    public static void setAuthKey(String authorization) {
        set("AuthKey", authorization);
    }

    public static void setLoginUser(LoginInfo loginUser) {
        set("login_user", loginUser);
    }

    private static String returnObjectValue(Object value) {
        return value == null ? "" : value.toString();
    }

    public static void remove() {
        threadLocal.remove();
    }
}
